﻿package{
	import flash.events.*;
	import flash.net.*;
	
	public class databaseComm {  //methods for talking to the database - untested with php files
		
		public var highScore:int = 0;
		
		//method for getting the high score from the database
		public function getHighScore():int{	
			// address path to the php script on a server - change this to your server
			var a:String = "http://www.cionodesigns.com/cs4911-facebook-game/getHighScore.php";
			//trace(a);
			var scriptRequest:URLRequest = new URLRequest(a);
			scriptRequest.method = URLRequestMethod.GET;
			var scriptLoader:URLLoader = new URLLoader();
			scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
			scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
			
			scriptLoader.load(scriptRequest);
			//trace(scriptRequest.data.toString());
			
			//trace("highscore from server is " + highScore.toString());
			return highScore;
		}
		
		//method for setting the high score by saving it to the server
		public function setHighScore(score:int):void{
			// address path to the php script on a server - change this to your server
			var scriptRequest:URLRequest = new URLRequest("http://www.cionodesigns.com/cionodesigns/setHighScore.php");
			var scriptLoader:URLLoader = new URLLoader();
			var scriptVars:URLVariables = new URLVariables();
			
			//scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
			scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
			
			scriptVars.score = score;
			//trace("highscore to server is " + score.toString());

			scriptRequest.method = URLRequestMethod.POST;
			scriptRequest.data = scriptVars;
			scriptLoader.load(scriptRequest);
		}
		
		//upon the php script finishing, this method grabs the variable from the return string from the php script
		function handleLoadSuccessful($evt:Event):void
		{
			//TO DO: add to the end of $evt.target.data the variable name used in the return string from the php script
			//		to pass it to the global variable highScore
			//var temp = $evt.target.data;
			highScore = $evt.target.data;
    		//trace("Got Response " + temp);//highScore.toString());
		} 

		function handleLoadError($evt:IOErrorEvent):void
		{
    		//trace("Connection to database failed.");
		}

	}
}